var Faye = require('faye')
var HOST = '127.0.0.1';     //定义服务器地址
var client = new Faye.Client('http://' + HOST + ':3344/events');
var fs = require("fs");

require('./mock_client')

console.log("BASE  BASE");
var avr = [];
var currentTime;

var timeNum = {
    "$GNGGA": 1,
    "$PASHR": 4,
    "$PASHD": 2,
    "$PTNL": 2,
    "$GPGGA": 1
};

function sortNumber(a, b) {
    return a[1] - b[1]
}

client.subscribe('/station', function (message) {

    var lines = message.data.split('\r\n');

    var key;

    for (var i = 0; i < lines.length; i++) {
        var line = lines[i].split(',');

        var time = line[timeNum[line[0]]].substring(0, line[timeNum[line[0]]].length - 3);

        if (!currentTime || currentTime !== time) {
            console.log('------set time')
            currentTime = time;
            avr = [];
        }

        if (line.length < 5) {
            continue;
        }

        if (line[4].indexOf("BEG*") !== -1 && line[1] === "#1") {
            key = line[1];
            continue
        }

        if (line[1] === "AVR" && key === "#1") {
            var info = lines[i].split(",");
            avr.push([info[2], info[3], info[9]]);
        } else {
            key = undefined;
        }
    }
    if (avr.length === 10) {
        var sortAvr = avr.sort(sortNumber);
        sortAvr.shift();
        sortAvr.pop();

        var sum =0;
        var sum2 =0;
        for(var t=0;t<sortAvr.length;t++){
            sum+=Number(sortAvr[t][1])
            sum2+=Number(sortAvr[t][2])
        }

        client.publish('/node', {
            data: [sortAvr[0][0],(sum/sortAvr.length).toFixed(4),(sum2/sortAvr.length).toFixed(4)],
            updateTime: new Date().getTime()
        })
    }


})
